# coding:utf-8
import gzip
import json
import zlib
import StringIO


__author__ = 'lanzhi'

import hashlib
import time
from urllib import parse, request, error

# reload(sys)
# sys.setdefaultencoding('utf8')
appkey = '*'
# 生产
appsecret = '*'


# uat
# appsecret = 'xxx'


def send_request(method, url, **args):
    headers = {
               'Connection': 'keep-alive',
               }
    data = {
        'appkey': appkey,
        'ts': int(time.time()),
        #  secret不要显示在地址栏中
        # 'appsecret': appsecret,
    }
    # 加密
    data.update(args)
    # 排序
    data_sort = parse.urlencode(sorted(data.items(), key=lambda d: d[0]))
    # print data_sort
    # MD5加密
    m2 = hashlib.md5()
    # m2.update(data_sort.lower() + appsecret)
    m2.update((data_sort + appsecret).encode("utf8"))
    sign = m2.hexdigest()
    # 完事

    # 把sign加进dict，进行urlencode编码
    data['sign'] = sign
    # data.pop('appsecret')
    print(data)
    params = parse.urlencode(data)
    print(url + '?' + params)
    if method == 'get':
        url = url + '?' + params
        http_request = request.Request(url, headers=headers)
    elif method == 'post':
        http_request = request.Request(url, params, headers=headers)
    else:
        return "wrong httpRequest request type"
    global e
    try:
        response = request.urlopen(http_request)
        encode = response.headers.get('Content-Encoding')
        print encode
        if encode == 'gzip':
            compresseddata = response.read()
            compressedstream = StringIO.StringIO(compresseddata)
            gzipper = gzip.GzipFile(fileobj=compressedstream)
            data = gzipper.read()
        elif encode == 'deflate':
            compresseddata = response.read()
            data = zlib.decompress(compresseddata, -zlib.MAX_WBITS)
        else:
            data = response.read()
        return data
        return response.read()
    except error.HTTPError as e:
        print('HTTPError：' + e.code)
    except error.URLError as e:
        print('URLError：' + e.reason)
    if e.reason == 'Not Found':
        case = 'connect'
        print([case, 'Page Not Found!!'])
    else:
        print('connect is OK ~!')


if __name__ == '__main__':
    print('-----------start----------------')
    url = 'http://api.bilibili.com/pgc/season/app/related/recommend'
    # url = 'http://localhost:8081/pgc/season/app``1`/related/recommend'
    response = send_request('get', url, season_id=6455, device="123", mobi_app="android", build=60000000)
    response = json.loads(response)

    # url = 'http://show.xxx.com/api/ticket/sug/seasonV2'
    # response = send_request('get', url, season_id=24311, mid="123",buvid = 60000000 )
    # url = 'http://api.xxx.com/pgc/web/recommend/related/recommend'
    # url = 'http://api.xxx.co/x/internal/v1/audio/menus/by-season'
    # url = 'http://api.xxx.com/pgc/season/play/recommend'1asdasd`
    # response = send_request('get', url, season_id=20790)
    # response = send_request('get', url, season_id=24311)
    # response = send_request('get', url, id=24311, pageNum=1, pageSize=3)
    time.sleep(0.01)
    print(response)

    print("------finish--------------")
